/**
 * 调用方式： Wap.Geo(function(meta){
 *     // meta = {"location":{"lng":116.911468,"lat":34.700648},"formatted_address":"江苏省南京市玄武区","business":"","addressComponent":{"city":"南京市","district":"玄武区","province":"江苏省","street":"","street_number":""},"cityCode":316};
 * });
 */
;(function(M,W){
    M.Geo = function(callback){
        var Geo = function(callback){
            this.callback = callback;
            this.isGeo = false;
            //定位出来的默认值
            this._postDataDefault = {"location":{"longi":116.911468,"lati":34.700648},"formatted_address":"江苏省南京市玄武区","business":"","addressComponent":{"city":"南京市","district":"玄武区","province":"江苏省","street":"","street_number":""},"cityCode":316, "cityNo":"9173","mdmCityNo":"1000173","provinceCode": "100"};

            //不支持导航定位，采用IP定位
            if(!navigator.geolocation){
                this.getPositionByIp(true);
            }else{
                //采用导航定位
                navigator.geolocation.getCurrentPosition($.proxy(this.showPosition,this), $.proxy(this.locationError,this),{
                timeout: 3000,
                maximumAge:86400000
            });
            }
            this.navError();
        }

        Geo.prototype = {
          locationError: function(error){
              this.isGeo = true;
                switch(error.code) {
                    case error.TIMEOUT:
                        this.getPositionByIp(true);
                        break;
                    case error.POSITION_UNAVAILABLE:
                        // 无法定位
                        this.getPositionByIp(true);
                        break;
                    case error.PERMISSION_DENIED:
                        // 对网站永久拒绝定位服务或者暂时拒绝定位服务
                        this.getPositionByIp(false);
                        break;
                    case error.UNKNOWN_ERROR:
                        this.getPositionByIp(true);
                        break;
                    default:
                        this.getPositionByIp(true);
                        break;
                }
          },
          showPosition:function(position) {
                var self = this;
                self.isGeo = true;

                //alert(position.coords.latitude + '------'+position.coords.longitude);
                var pos = {
                    lati: position.coords.latitude,
                    longi: position.coords.longitude
                };
                $.ajax({
                    type : "GET",
                    url : "//api.map.baidu.com/geocoder/v2/?ak=358795dcf3df541d1551c0cd052aee95&callback=jsonpCallback&location=" + pos.lati + "," + pos.longi + "&output=json&pois=0",
                    cache : true,
                    async : true,
                    timeout: 3000,
                    dataType : "jsonp",
                    jsonp:false,
                    jsonpCallback : "jsonpCallback",
                    success : function(posData){
                        $.ajax({
                            url: "//ipservice.suning.com/provinceList-provinceListCallback.htm",
                            type: "GET",
                            cache: true,
                            async: true,
                            dataType: "jsonp",
                            jsonp: false,
                            jsonpCallback: "provinceListCallback"
                        }).done(function(data){
                            $(data.provinces).each(function(index, item){

                                var provName = posData.result.addressComponent.province.slice(0,-1);

                                if(item.name.indexOf(provName) > -1){
                                    $.ajax({
                                        url: "//ipservice.suning.com/cityList-" + item.mdmId + "_20150401-cityListCallback.htm",
                                        type: "GET",
                                        cache: true,
                                        async: true,
                                        dataType: "jsonp",
                                        jsonp: false,
                                        jsonpCallback: "cityListCallback",
                                    }).done(function(data){
                                    		//alert(posData.result.cityCode + '------'+ posData.result.addressComponent.city);
                                        $(data.cities).each(function(index, item){
                                            var _cityName_ =  posData.result.addressComponent.city.slice(0,-1);
                                            if( item.name.indexOf(_cityName_) > -1 ){
                                                posData.result.cityNo = item.commerceId;
                                                posData.result.provinceCode = item.provinceMdmId;
                                                posData.result.cityName = item.name;
												posData.result.mdmCityNo = item.mdmId;
                                                self.callback(posData.result);
                                            }
                                            return false;
                                        })
                                    });
                                    return false;
                                }
                            })
                        }).fail(function(){
                            self.getPositionByIp(true);
                        });
                        
                    },
                    error : function(XMLHttpRequest, textStatus, errorThrown){
                        self.getPositionByIp(true);
                    }
                });
            },
          getPositionByIp:function(isAlert){
              //TODO:直接测试返回假数据，真实环境需要配置${wap.geo.ip.intf.url}，发起请求
//              this.callback(this._postDataDefault);
            this.isGeo = true;
            var _this = this;
            setTimeout(function(){
                $.ajax({
                    type : "GET",
                    url : "//ipservice.suning.com/ipQuery.do",
                    cache : true,
                    dataType : "jsonp",
                    jsonpCallback : "jsonpCallback",
                    success : function(ipData){
                        // alert("IP")
//                        if(isAlert == true){
//                        	alert("当前定位城市为" + ipData.cityName);
//                        }
                        _this._postDataDefault.cityNo = ipData.cityCommerceId;
                        _this._postDataDefault.provinceCode = ipData.provinceCommerceId;
                        _this._postDataDefault.cityName = ipData.cityName;
						_this._postDataDefault.mdmCityNo = ipData.cityMDMId;
                        // alert("ip")
                        _this.callback(_this._postDataDefault);
                    },
                    error : function() {
                        if(isAlert == true){
                        	alert("很抱歉无法定位当前城市");
                        }
                        _this.callback(_this._postDataDefault);
                    }
                });
            },100);

        },
        /**
         * H5 Nav定位出错处理。过2秒后，扫描是否定位到数据，没有定位到，走IP定位
         */
       navError:function(){
        
        var _this = this;
           setTimeout(function(){
               if(!_this.isGeo){
                console.log("Geo app");
                   _this.getPositionByIp(true);
               }
           },5000)
       }

        }

        return new Geo(callback);
    }

}(window.Wap = window.Wap || {}, window))